package com.yiwu.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiwu.common.component.ElasticComponent;
import com.yiwu.common.domain.dto.ProductDTO;
import com.yiwu.common.domain.entity.Products;
import com.yiwu.common.domain.entity.UserFavorites;
import com.yiwu.common.domain.mapper.ProductsMapper;
import com.yiwu.common.domain.mapper.UserFavoritesMapper;
import com.yiwu.common.enums.ResponseCode;
import com.yiwu.common.exception.BusinessException;
import com.yiwu.common.model.vo.product.*;
import com.yiwu.web.service.ProductsService;
import jakarta.annotation.Resource;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 咏鹅
 * @description 针对表【Products】的数据库操作Service实现
 * @createDate 2024-05-18 21:09:40
 */
@Service
public class ProductsServiceImpl implements ProductsService {
    @Resource
    private ProductsMapper productsMapper;

    @Resource
    private UserFavoritesMapper userFavoritesMapper;

    @Resource
    private ElasticComponent elasticComponent;

    @Override
    public String addProduct(ProductAddReqVO productAddReqVO, Long sellerId) {
        Products products = new Products();
        BeanUtils.copyProperties(productAddReqVO, products);
        products.setSellerId(sellerId);
        String[] imageUrls = productAddReqVO.getImageUrl();
        StringBuilder sb = new StringBuilder();
        int length = imageUrls.length;
        for (int i = 0; i < length - 1; i++) {
            sb.append(imageUrls[i]).append(";");
        }
        sb.append(imageUrls[length - 1]);
        products.setImageUrl(sb.toString());
        products.insert();
        return products.getProductId().toString();
    }

    @Override
    public ProductImageRspVO getProductDetailsById(String productId) {

        ProductDTO productDTO = productsMapper.selectProductDetailsById(productId);
        QueryWrapper<UserFavorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        Long favoriteCount = userFavoritesMapper.selectCount(queryWrapper);
        queryWrapper.eq("user_id", 1);
        Long isFavorite = userFavoritesMapper.selectCount(queryWrapper);
        ProductImageRspVO productImageDTO = new ProductImageRspVO();
        BeanUtils.copyProperties(productDTO, productImageDTO);

        productImageDTO.setProductId(productDTO.getProductId().toString());
        productImageDTO.setSellerId(productDTO.getSellerId().toString());
        productImageDTO.setFavoriteCount(favoriteCount.intValue());
        if (isFavorite != 0) {
            productImageDTO.setFavorite(true);
        }

        String imageUrl = productDTO.getImageUrl();
        String[] productSplit = imageUrl.split(";");
        productImageDTO.setImageUrl(productSplit);


        return productImageDTO;
    }

    @Override
    public List<ProductAllRspVO> getAllProduct(ProductAllReqVO productAllReqVO) {
        Long current = productAllReqVO.getCurrent();
        Long size = productAllReqVO.getSize();
        String description = productAllReqVO.getDescription();
        Integer categoryId = productAllReqVO.getCategoryId();
        LocalDate startDate = productAllReqVO.getStartDate();
        LocalDate endDate = productAllReqVO.getEndDate();

        Page<Products> productsPage = productsMapper.selectPageProductList(current, size, null, description, categoryId, 0, startDate, endDate);
        List<Products> productsDoS = productsPage.getRecords();

        List<ProductAllRspVO> productAllRspVOS = null;
        //DO 转VO
        if (!CollectionUtils.isEmpty(productsDoS)) {
            productAllRspVOS = productsDoS.stream()
                    .map(pdo -> ProductAllRspVO.builder()
                            .productId(pdo.getProductId().toString())
                            .categoryId(pdo.getCategoryId())
                            .price(pdo.getPrice())
                            .description(pdo.getDescription())
                            .imageUrl(pdo.getImageUrl() == null ? "" : pdo.getImageUrl().split(";")[0])
                            .description(pdo.getDescription())
                            .createdAt(pdo.getCreatedAt())
                            .build())
                    .toList();
        }

        return productAllRspVOS;
    }

    @Override
    public Boolean updateProductStatus(ProductReqVO productReqVO, Integer status, Long sellerId) {
        Long productId = productReqVO.getProductId();
        if (productId == null) return false;
        if (sellerId == null) return false;
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId)
                .eq("seller_id", sellerId);
        Products products = productsMapper.selectOne(queryWrapper);
        if (Objects.isNull(products)) return false;

        products.markStatus(status);
        products.updateById();
        return true;
    }

    @Override
    public List<ProductAllRspVO> getMyProductList(ProductAllReqVO productAllReqVO, Long userId) {
        Long current = productAllReqVO.getCurrent();
        Long size = productAllReqVO.getSize();

        String description = productAllReqVO.getDescription();
        Integer categoryId = productAllReqVO.getCategoryId();
        LocalDate startDate = productAllReqVO.getStartDate();
        LocalDate endDate = productAllReqVO.getEndDate();

        Page<Products> productsPage = productsMapper.selectPageProductList(current, size, userId, description, categoryId, null, startDate, endDate);
        List<Products> productsDoS = productsPage.getRecords();

        //DO 转VO
        if (!CollectionUtils.isEmpty(productsDoS)) {
            return productsDoS.stream()
                    .map(pdo -> ProductAllRspVO.builder()
                            .productId(pdo.getProductId().toString())
                            .categoryId(pdo.getCategoryId())
                            .price(pdo.getPrice())
                            .pstatus(pdo.getPstatus())
                            .description(pdo.getDescription())
                            .imageUrl(pdo.getImageUrl() == null ? "" : pdo.getImageUrl().split(";")[0])
                            .description(pdo.getDescription())
                            .createdAt(pdo.getCreatedAt())
                            .build())
                    .toList();
        }

        return new ArrayList<>();
    }

    @Override
    public List<ProductAllRspVO> getSellerProductList(ProductSellerReqVO productSellerReqVO) {
        Page<Products> productsPage = new Page<>(productSellerReqVO.getCurrent(),productSellerReqVO.getSize());
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seller_id", productSellerReqVO.getSellerId());
        queryWrapper.eq("pstatus",0);
        queryWrapper.orderByDesc("created_at");
        queryWrapper.ne(Strings.isNotEmpty(productSellerReqVO.getProductId()),"product_id",productSellerReqVO.getProductId());

        List<Products> products = productsMapper.selectPage(productsPage,queryWrapper).getRecords();
        List<ProductAllRspVO> productAllRspVOS = new ArrayList<>();
        if (products != null) {
            productAllRspVOS = products.stream().map(pdo -> ProductAllRspVO.builder()
                            .productId(pdo.getProductId().toString())
                            .imageUrl(pdo.getImageUrl() == null ? "" : pdo.getImageUrl().split(";")[0])
                            .categoryId(pdo.getCategoryId())
                            .price(pdo.getPrice())
                            .description(pdo.getDescription())
                            .pstatus(pdo.getPstatus())
                            .createdAt(pdo.getCreatedAt())
                            .build())
                    .toList();
        }
        return productAllRspVOS;
    }

    @Override
    public List<ProductAllRspVO> getRecommendProductList(String productId) {
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.notIn("product_id", productId);
        List<Products> products = productsMapper.selectList(queryWrapper);
        List<ProductAllRspVO> productAllRspVOS = new ArrayList<>();
        if (products != null) {
            productAllRspVOS = products.stream().map(pdo -> ProductAllRspVO.builder()
                            .productId(pdo.getProductId().toString())
                            .categoryId(pdo.getCategoryId())
                            .imageUrl(pdo.getImageUrl() == null ? "" : pdo.getImageUrl().split(";")[0])
                            .price(pdo.getPrice())
                            .description(pdo.getDescription())
                            .createdAt(pdo.getCreatedAt())
                            .build())
                    .toList();
        }
        return productAllRspVOS;
    }

    @Override
    public List<String> searchKeySuggest(String keyword) {
        try{
         return elasticComponent.getSuggestions("product","suggest",keyword);
        }catch (Exception e){
            throw new BusinessException(ResponseCode.PARAMETER_ERROR);
        }
    }
}




